<?php

// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------  

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\NodeService;
use service\ToolsService;
use think\Db;
use think\View;

/**
 * 后台入口
 * Class Index
 * @package app\admin\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/02/15 10:41
 */
class Index extends BasicAdmin
{

    /**
     * 后台框架布局
     * @return View
     */
    public function index()
    {
        if(!session('user')) {
            $this->redirect('@admin/login/index');
        }
        NodeService::applyAuthNode();
        $list = (array) Db::name('SystemMenu')->where(['status' => '1'])->order('sort asc,id asc')->select();
        $menus = $this->_filterMenuData(ToolsService::arr2tree($list), NodeService::get(), !!session('user'));
//        halt(ToolsService::arr2tree($list));
//        halt(NodeService::get());
//        halt(ToolsService::arr2tree($list));
//        halt(NodeService::get());       //store/index/post
        // return $this->fetch('index');
        return view('', ['title' => '系统管理', 'menus' => $menus]);
    }

    /**
     * 后台主菜单权限过滤
     * @param array $menus 当前菜单列表
     * @param array $nodes 系统权限节点数据
     * @param bool $isLogin 是否已经登录
     * @return array
     */
    private function _filterMenuData($menus, $nodes, $isLogin)
    {
        foreach ($menus as $key => &$menu) {
            !empty($menu['sub']) && $menu['sub'] = $this->_filterMenuData($menu['sub'], $nodes, $isLogin);
            if (!empty($menu['sub'])) {
                $menu['url'] = '#';
            } elseif (preg_match('/^https?\:/i', $menu['url'])) {
                continue;
            } elseif ($menu['url'] !== '#') {
                $node = join('/', array_slice(explode('/', preg_replace('/[\W]/', '/', $menu['url'])), 0, 3));
                $menu['url'] = url($menu['url']);
                if (isset($nodes[$node]) && $nodes[$node]['is_login'] && empty($isLogin)) {
                    unset($menus[$key]);
                } elseif (isset($nodes[$node]) && $nodes[$node]['is_auth'] && $isLogin && !auth($node)) {
                    unset($menus[$key]);
                }
            } else {
                unset($menus[$key]);
            }
        }
        return $menus;
    }

    /**
     * 主机信息显示
     * @return View
     * 统计会员数，本月新增，总的交易完成订单数，交易额，
     */
    public function main()
    {
        if(session('user.store_id') == 0){      //总消费量
            $all_member = db('user')->where(['is_deleted'=>0])->count();
            $month_member = db('user')->where(['is_deleted'=>0])->whereTime('addtime','m')->count();
            $all_order = db('order')->where(['order_status'=>['egt',4]])->whereTime('pay_time','m')->count();
            $month_online_order = db('order')->where(['order_status'=>['egt',4],'order_type'=>1])->count();      //线上订单
            $month_underline_amount = db('order')->where(['order_status'=>['egt',4],'order_type'=>0])->whereTime('pay_time','m')->sum('final_amount');
            $all_amount = $month_online_order+$month_underline_amount;
            $title = '后台首页 - 统计数据';

        }else{          //门店消费量
            $all_member = db('user')->where(['is_deleted'=>0,'store_id'=>session('user.store_id')])->count();
            $month_member = db('user')->where(['is_deleted'=>0,'store_id'=>session('user.store_id')])->whereTime('addtime','m')->count();
            $all_order = db('order')->where(['order_status'=>['egt',4],'store_id'=>session('user.store_id')])->whereTime('pay_time','m')->count();
            $month_online_order = db('order')->where(['order_status'=>['egt',4],'order_type'=>1,'store_id'=>session('user.store_id')])->count();      //线上订单
            $month_underline_amount = db('order')->where(['order_status'=>['egt',4],'order_type'=>0,'store_id'=>session('user.store_id')])->whereTime('pay_time','m')->sum('final_amount');
            $all_amount = $month_online_order+$month_underline_amount;
            $store = db('store')->where('id',session('user.store_id'))->value('title');
            $title = '后台首页 - '.$store.'- 统计数据';
        }
        $_version = Db::query('select version() as ver');
        return view('', ['mysql_ver' => array_pop($_version)['ver'], 'title' => $title,'all_member'=>$all_member,'month_member'=>$month_member,'all_order'=>$all_order,'all_amount'=>$all_amount,'month_online_order'=>$month_online_order,'month_underline_amount'=>$month_underline_amount]);
    }

    /**
     * 修改密码
     */
    public function pass()
    {
        if (intval($this->request->request('id')) !== intval(session('user.id'))) {
            $this->error('只能修改当前用户的密码！');
        }
        if ($this->request->isGet()) {
            $this->assign('verify', true);
            return $this->_form('SystemUser', 'user/pass');
        }
        $data = $this->request->post();
        if ($data['password'] !== $data['repassword']) {
            $this->error('两次输入的密码不一致，请重新输入！');
        }
        $user = Db::name('SystemUser')->where('id', session('user.id'))->find();
        if (md5($data['oldpassword']) !== $user['password']) {
            $this->error('旧密码验证失败，请重新输入！');
        }
        if (DataService::save('SystemUser', ['id' => session('user.id'), 'password' => md5($data['password'])])) {
            $this->success('密码修改成功，下次请使用新密码登录！', '');
        }
        $this->error('密码修改失败，请稍候再试！');
    }

    /**
     * 修改资料
     */
    public function info()
    {
        if (intval($this->request->request('id')) === intval(session('user.id'))) {
            return $this->_form('SystemUser', 'user/form');
        }
        $this->error('只能修改当前用户的资料！');
    }

    public function echart1(){
        return $this->fetch();
    }

    /**
     * @Author  lingyun
     * @Desc    本月线上营业额
     * @return mixed
     */
    public function online_order(){
        $time = $this->get_month_time();
        $map = " and pay_time>".$time['start']." and pay_time<".$time['end']." and order_type=1";

        if(session('user.store_id') == ''){         //总订单统计
            $sql = "select FROM_UNIXTIME(pay_time,'%d') AS hours, sum(final_amount-tuihuo_amount) as totalmoney, count(*) as num from ys_order WHERE order_status>=4 ".$map." group by hours ORDER BY hours";
        }else{          //分订单统计
            $sql = "select FROM_UNIXTIME(pay_time,'%d') AS hours, sum(final_amount-tuihuo_amount) as totalmoney, count(*) as num from ys_order WHERE store_id=" . session('user.store_id') ." and order_status>=4 ". $map . " group by hours ORDER BY hours";
        }

        $db = Db::query($sql);

        $dt_start = $time['start'];
        $dt_end = $time['end'];
        $dates = [];
        while ($dt_start <= $dt_end) {
            $dates[] = date('d', $dt_start);
            $dt_start = strtotime('+1 day', $dt_start);
        }

        foreach ($db as $key => $value) {
            $ndb[$value['hours']]['totalmoney'] = $value['totalmoney'];
            $ndb[$value['hours']]['num'] = $value['num'];
        }

        foreach ($dates as $value) {
            if (!isset($ndb[$value])) {
                $ndb[$value]['totalmoney'] = '0.00';
                $ndb[$value]['num'] = 0;
            }
        }

        ksort($ndb);

        $max_amount = 0;            //最高交易额
        $max_num = 0;               //最高交易量
        foreach ($ndb as $key => $value) {
            $days[] = (string)$key;
            $totalmoney[] = $value['totalmoney'];
            $totalnum[] = (string)$value['num'];
            if($value['totalmoney']>$max_amount){
                $max_amount = $value['totalmoney'];
            }
            if($value['num']>$max_num){
                $max_num = $value['num'];
            }
        }

        $this->assign('days', json_encode($days));
        $this->assign('totalmoney', json_encode($totalmoney));
        $this->assign('totalnum', json_encode($totalnum));
        $this->assign('max_amount', $max_amount);
        $this->assign('max_num', $max_num);

        return $this->fetch();
    }

    /**
     * @Author  lingyun
     * @Desc    本月线下营业额
     * 2018-05-14
     */
    public function underline_order(){
        $time = $this->get_month_time();
        $map = " and pay_time>".$time['start']." and pay_time<".$time['end']." and order_type=0";

        if(session('user.store_id') == ''){         //总订单统计
            $sql = "select FROM_UNIXTIME(pay_time,'%d') AS hours, sum(final_amount-tuihuo_amount) as totalmoney, count(*) as num from ys_order WHERE order_status>=4 ".$map." group by hours ORDER BY hours";
        }else{          //分订单统计
            $sql = "select FROM_UNIXTIME(pay_time,'%d') AS hours, sum(final_amount-tuihuo_amount) as totalmoney, count(*) as num from ys_order WHERE store_id=" . session('user.store_id') ." and order_status>=4 ". $map . " group by hours ORDER BY hours";
        }

        $db = Db::query($sql);

        $dt_start = $time['start'];
        $dt_end = $time['end'];
        $dates = [];
        while ($dt_start <= $dt_end) {
            $dates[] = date('d', $dt_start);
            $dt_start = strtotime('+1 day', $dt_start);
        }

        foreach ($db as $key => $value) {
            $ndb[$value['hours']]['totalmoney'] = $value['totalmoney'];
            $ndb[$value['hours']]['num'] = $value['num'];
        }

        foreach ($dates as $value) {
            if (!isset($ndb[$value])) {
                $ndb[$value]['totalmoney'] = '0.00';
                $ndb[$value]['num'] = 0;
            }
        }

        ksort($ndb);

        $max_amount = 0;            //最高交易额
        $max_num = 0;               //最高交易量
        foreach ($ndb as $key => $value) {
            $days[] = (string)$key;
            $totalmoney[] = $value['totalmoney'];
            $totalnum[] = (string)$value['num'];
            if($value['totalmoney']>$max_amount){
                $max_amount = $value['totalmoney'];
            }
            if($value['num']>$max_num){
                $max_num = $value['num'];
            }
        }

        $this->assign('days', json_encode($days));
        $this->assign('totalmoney', json_encode($totalmoney));
        $this->assign('totalnum', json_encode($totalnum));
        $this->assign('max_amount', $max_amount);
        $this->assign('max_num', $max_num);

        return $this->fetch();
    }

    /**
     * @Author  lingyun
     * @Desc    新注册会员统计
     * 2018-05-14
     */
    public function new_member(){
        $time = $this->get_month_time();
        $map = " and addtime>".$time['start']." and addtime<".$time['end'];

        $sql = "select FROM_UNIXTIME(addtime,'%d') AS hours,  count(*) as num from ys_user WHERE is_deleted=0 ".$map." group by hours ORDER BY hours";

        $db = Db::query($sql);

        $dt_start = $time['start'];
        $dt_end = $time['end'];
        $dates = [];
        while ($dt_start <= $dt_end) {
            $dates[] = date('d', $dt_start);
            $dt_start = strtotime('+1 day', $dt_start);
        }

        foreach ($db as $key => $value) {
            $ndb[$value['hours']]['num'] = $value['num'];
        }

        foreach ($dates as $value) {
            if (!isset($ndb[$value])) {
                $ndb[$value]['num'] = '0';
            }
        }

        ksort($ndb);

        $max_amount = 0;            //最高交易额
        $max_num = 0;               //最高交易量
        foreach ($ndb as $key => $value) {
            $days[] = (string)$key;
            $totalnum[] = (string)$value['num'];
            if($value['num']>$max_num){
                $max_num = $value['num'];
            }
        }

        $this->assign('days', json_encode($days));
        $this->assign('totalnum', json_encode($totalnum));
        $this->assign('max_num', $max_num);

        return $this->fetch();
    }

    /**
     * @Author  lingyun
     * @Desc    门店营业排行统计
     */
    public function store_order(){
        $time = $this->get_month_time();
        $map = " and a.pay_time>".$time['start']." and a.pay_time<".$time['end'];
        $store = db('store')->where(['is_deleted'=>0])->column('id,title');

        $sql = "select  sum(a.final_amount-a.tuihuo_amount) as totalmoney,b.id,b.title, count(*) as num from ys_order as a left join ys_store as b on a.store_id=b.id WHERE a.order_status>=4 ".$map." group by b.id ORDER BY b.id asc";

        $db = Db::query($sql);

        foreach ($db as $key => $value) {
            $ndb[$value['id']]['totalmoney'] = $value['totalmoney'];
            $ndb[$value['id']]['num'] = $value['num'];
            $ndb[$value['id']]['title'] = $value['title'];
        }

        ksort($ndb);

        foreach ($store as $value => $v) {
            if (!isset($ndb[$value])) {
                $ndb[$value]['num'] = '0';
                $ndb[$value]['totalmoney'] = '0';
                $ndb[$value]['title'] = $v;
            }
        }
        $max_amount = 0;            //最高交易额
        $max_num = 0;               //最高交易量
        foreach ($ndb as $key => $value) {
            $title[] = (string)$value['title'];
            $totalmoney[] = $value['totalmoney'];
            $totalnum[] = (string)$value['num'];
            if($value['totalmoney']>$max_amount){
                $max_amount = $value['totalmoney'];
            }
            if($value['num']>$max_num){
                $max_num = $value['num'];
            }
        }

        $this->assign('title', json_encode($title));
        $this->assign('totalmoney', json_encode($totalmoney));
        $this->assign('totalnum', json_encode($totalnum));
        $this->assign('max_amount', $max_amount);
        $this->assign('max_num', $max_num);

        return $this->fetch();
    }

    /**
     * @Author  lingyun
     * @Desc    获取本月的起止时间
     * @return array
     */
    private function get_month_time(){
        $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
        $endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));

        return ['start'=>$beginThismonth,'end'=>$endThismonth];
    }


}
